package com.whf.android.jar.idempotent;

import android.os.CountDownTimer;

import com.whf.android.jar.popup.listener.OnClickDecisionListener;
import com.whf.android.jar.util.FormatUtil;
import com.whf.android.jar.util.number.DoubleUtils;

/**
 * 支付倒计时
 *
 * @author qf
 * @version 1.0.3
 */
public class LatteCountDown extends CountDownTimer {

    private static boolean idempotent = false;
    private final OnClickDecisionListener mClickDecisionListener;

    public static void init(long millisInFuture, OnClickDecisionListener listener) {
        if (idempotent) {
            return;
        }
        new LatteCountDown(millisInFuture, listener).start();
    }

    /**
     * @param millisInFuture The number of millis in the future from the call
     *                       to {@link #start()} until the countdown is done and {@link #onFinish()}
     *                       is called.
     */
    public LatteCountDown(long millisInFuture, OnClickDecisionListener listener) {
        super(millisInFuture, 1000);
        this.mClickDecisionListener = listener;
    }

    @Override
    public void onTick(long millisUntilFinished) {
        idempotent = true;
        long second = DoubleUtils.objToLong(DoubleUtils.div(millisUntilFinished, 1000));
        String minuteSecond = FormatUtil.string2Seconds(second);
        if (mClickDecisionListener != null) {
            mClickDecisionListener.onConfirm(minuteSecond);
        }
    }

    @Override
    public void onFinish() {
        idempotent = false;
        if (mClickDecisionListener != null) {
            mClickDecisionListener.onCancel();
        }
    }
}
